'''
Created on May 15, 2010

iur - Universal Web Remote targetted for iphone
Copyright (C) 2010 forteresce@gmail.com

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 3
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

'''

from player.eventhandler import PlayerEventHandler
from model.song import Song
import dbus

class RhythmboxEventHandler(PlayerEventHandler):
    '''
    The event handler for Rhythmbox player
    '''
    DBUS_NAME   = 'org.gnome.Rhythmbox'
    PLAYER_DBUS_OBJECT = '/org/gnome/Rhythmbox/Player'
    SHELL_DBUS_OBJECT = '/org/gnome/Rhythmbox/Shell'
    
    def __init__(self):
        self.player = self.session_bus.get_object(self.DBUS_NAME, self.PLAYER_DBUS_OBJECT)
        self.shell = self.session_bus.get_object(self.DBUS_NAME, self.SHELL_DBUS_OBJECT)
        pass
    
    def play(self):
        self.player.playPause(True)
    
    def pause(self):
        self.player.playPause(True)

    def next(self):
        self.player.next()

    def prev(self):
        self.player.previous()    

    def getCurrentSong(self):
        if not self.player.getPlaying():
            return
        
        track = self.shell.getSongProperties(self.player.getPlayingUri())
        
        # clean up
        vals = ('title','artist','album')
        for key in [key for key in vals if key not in track]:
            track[key] = 'Unknown'
            
        return Song(track['title'], track['artist'], track['album'])
    
    def addSongToQueue(self, id):
        uri = base64.b64decode(id)
        self.shell.addToQueue(uri)

    def volumeUp(self):
        self.player.setVolumeRelative(dbus.Double(0.1))
        return int(self.player.getVolume()*100)

    def volumeDown(self):
        self.player.setVolumeRelative(dbus.Double(-0.1))
        return int(self.player.getVolume()*100)


#====================================================================================================

from player.collectionhandler import PlayerCollectionHandler
import os
from model.album import Album
from xml.etree.ElementTree import ElementTree
import base64

class RhythmboxCollectionHandler(PlayerCollectionHandler):
    '''
    The collection handler for Rhythmbox player
    '''
    DB_PATH = os.path.join(os.path.expanduser('~'), '.local', 'share', 'rhythmbox', 'rhythmdb.xml')
    
    def __init__(self):
        self.rhythmdb = ElementTree().parse(self.DB_PATH)
        
    def getAlbums(self, startsWith='a'):
        albumNames = set()
        entries = self.rhythmdb.findall('entry/album')
        
        for entry in entries:
            if entry.text is None:
                entry.text = 'Unknown'
            if entry.text.lower().startswith(startsWith.lower()):
                albumNames.add(entry.text)
            
        albums = []
        for name in albumNames:
            album = Album(base64.b64encode(name), name)
            albums.append(album)
        return albums
    
    def getSongsInAlbum(self, albumId):
        songs = []
        entries = self.rhythmdb.findall('entry')
        
        for entry in entries:
            album = entry.find("album").text if (entry.find("album").text is not None) else 'Unknown' 
            
            if album == base64.b64decode(albumId):
                title = entry.find("title").text if (entry.find("title").text is not None) else 'Unknown' 
                artist = entry.find("artist").text if (entry.find("artist").text is not None) else 'Unknown'
                location = entry.find("location").text if (entry.find("location").text is not None) else 'Unknown'
                song = Song(title, artist, album, base64.b64encode(location))
                songs.append(song)
            
        return songs
        